package boot.spring.service;

import boot.spring.config.LocalCache;
import boot.spring.consts.UserConstants;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.unfbx.chatgpt.OpenAiClient;
import com.unfbx.chatgpt.OpenAiStreamClient;
import com.unfbx.chatgpt.entity.chat.ChatCompletionResponse;
import com.unfbx.chatgpt.entity.chat.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ChatService {

    private static final Logger logger = LoggerFactory.getLogger(ChatService.class);

    private static final String apiKey = "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";
    private static final String apiHost = "https://api.openai.com/";

    private final OpenAiClient openAiClient = OpenAiClient.builder().apiHost(apiHost).apiKey(apiKey).build();

    private static final ChatService chatService = new ChatService();

    private ChatService() {

    }

    public static ChatService getInstance() {
        return chatService;
    }

    public String ask(String requestText) {
        logger.info("输入问题：{}", requestText);
        String messageContext = (String) LocalCache.CACHE.get(UserConstants.UID.toString());
        List<Message> messages = new ArrayList<>();
        if (StrUtil.isNotBlank(messageContext)) {
            messages = JSONUtil.toList(messageContext, Message.class);
            if (messages.size() >= 10) {
                messages = messages.subList(1, 10);
            }
            Message currentMessage = Message.builder().content(requestText).role(Message.Role.USER).build();
            messages.add(currentMessage);
        } else {
            Message currentMessage = Message.builder().content(requestText).role(Message.Role.USER).build();
            messages.add(currentMessage);
        }
        logger.debug("发送chat请求:{}", JSONUtil.toJsonStr(messages));
        ChatCompletionResponse completions = openAiClient.chatCompletion(messages);
        logger.debug("chat返回:{}", JSONUtil.toJsonStr(completions));
        //FIXME:完整的上下问应当记录回复信息，若资源消耗过多，可暂时不包含回复
        //messages.add(completions.getChoices().get(0).getMessage());
        LocalCache.CACHE.put(UserConstants.UID.toString(), JSONUtil.toJsonStr(messages));
        String reply =  completions.getChoices().get(0).getMessage().getContent();
//        String replyMsg = System.currentTimeMillis() + "默认随机回复";
        logger.info("返回回复:{}", reply);
        return reply;
    }
}
